package com.mima.minaserver.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.mima.minaserver.repository.RandomGeneRepository;
import com.mima.minaserver.repository.UUIDRepository;
import com.mima.minaserver.utils.ParameterUtils;

import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.CacheManager;

@Slf4j
@EnableScheduling
@Component
public class DeviceSafeUpdate {
	//private static Logger logger = LoggerFactory.getLogger(DeviceSafeUpdate.class);
	@Autowired
	private UUIDRepository uuidRepository;

	@Autowired
	private RandomGeneRepository randomGeneRepository;
	
	@Autowired
    CacheManager cacheManager;
	
	@Autowired
	IotServerMessage IotServerMessage;
	
	@Autowired
	AliCloudMessage AliCloudMessage;
	
	@Autowired
	ParameterUtils parameterUtils;

	/**
	 * 用户名，密码更新
	 */
	
	
	@Scheduled(cron = "0 0 1 * * ?")
	public void UpdateLonginInfo() {
		List<Object> uuid_keyId = uuidRepository.selectUUID();
		if (uuid_keyId != null && uuid_keyId.size() > 0) {
			for (Object object:uuid_keyId) { 
				Object[] results = (Object[])object;
				String myaccount = randomGeneRepository.RandomGeneration(6, true, true, true);
				String mypassword = randomGeneRepository.RandomGeneration(6, true, true, true);
				uuidRepository.updateSafeInfo(myaccount, mypassword, (String)results[0]);
			}
		}
	}
	
	
	/**
	 * 密钥更新
	 */
	@Scheduled(cron = "0 0 1 * * ?")
	public void UpdateKeyInfo() {
		List<Object> uuid_keyId = uuidRepository.selectUUID();
		if (uuid_keyId != null && uuid_keyId.size() >0) {
			for (Object object:uuid_keyId) {
				Object[] results = (Object[])object;
				String uuid = (String)results[0];
				int keyId = (int)results[1];
				keyId = generateKeyId(keyId);
				String secretkey = randomGeneRepository.RandomGeneration(1024, false, false, true);
				try {
					uuidRepository.updateSecretKey(secretkey,keyId, uuid);
				} catch (Exception e) {
					e.printStackTrace();
					return;
				}
				
			}
		}
	}
	
	private int generateKeyId(int count) {
		return count == 255 ? 1 : ++count;
	}
}
